<template>
  <div>
    <el-form label-position="right" label-width="80px">
      <el-row :gutter="8" v-if="outFilters && outFilters.length > 0">
        <el-col v-for="filter in outFilters" :span="6" :key="filter.filterId">
          <el-form-item :label="filter.filterName">
            <el-input-number v-if="filter.filterType === '数字'" v-model="args[filter.filterProp]" clearable style="width: 100%" controls-position="right"></el-input-number>
            <el-date-picker v-else-if="filter.filterType === '日期'" v-model="args[filter.filterProp]" type="date"  clearable style="width: 100%" value-format="yyyy-MM-dd" format="yyyy-MM-dd"></el-date-picker>
            <el-select v-else-if="filter.filterType === '选项'" v-model="args[filter.filterProp]" clearable style="width: 100%">
              <el-option v-for="option in filter.sources" :key="option.value" :value="option.value" :label="option.label" />
            </el-select>
            <el-input v-else-if="filter.filterType === '字符串'" v-model="args[filter.filterProp]" clearable></el-input>
            <div v-else>未支持字段</div>
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item v-else label="未配置搜索字段" label-width="120px"></el-form-item>
      <el-form-item style="width: 100%;text-align: center">
        <el-button :loading="loading" type="primary" icon="el-icon-search" @click="searchSource(false)">查询</el-button>
        <el-button :loading="loading" type="info" icon="el-icon-cpu" @click="searchSource(true)">计算</el-button>
        <el-button :loading="loading" type="warning" icon="el-icon-refresh-left" @click="clearArgs">重置</el-button>
        <el-button :loading="loading" type="success" icon="el-icon-download" @click="exportExcel">导出</el-button>
      </el-form-item>
    </el-form>
    <el-table ref="tableRef" class="bl-result" v-loading="loading" :data="pageInfo.dataSource" border :height="autoHeight">
      <template v-for="column in queryData.columns">
        <el-table-column :key="column.columnId" :label="column.columnTitle" :prop="column.columnTitle" align="center">
          <template slot-scope="scope">
            <div v-if="$Util.isEmpty(scope.row.cellStyle) || $Util.isEmpty(scope.row.cellStyle[column.columnTitle])">
              {{ scope.row[scope.column.property] }}
            </div>
            <div v-else :style="{ backgroundColor: scope.row.cellStyle[column.columnTitle].bgColor}" >
              {{ scope.row[scope.column.property] }}
            </div>
          </template>
        </el-table-column>
      </template>
    </el-table>
    <div class="lab-table-page">
      <div style="display: inline-flex">
        <el-pagination
            :disabled="loading"
            :current-page="pageInfo.page"
            :page-sizes="[20, 50, 100]"
            :page-size="pageInfo.pageSize"
            layout="total, sizes,prev, next"
            :total="pageInfo.total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
        />
      </div>
    </div>
  </div>
</template>

<script>

export default {
  name: "ResultTable",
  props: {
    excelOut: {
      type: Object,
      default: function () {
        return {}
      }
    }
  },
  data() {
    return {
      loading: false,
      args: {},
      queryData: { columns: [], datas: [] },
      outFilters: [],
      pageInfo: { page: 1, pageSize: 20, dataSource: [], total: 0 }
    }
  },
  computed: {
    autoHeight(){
      /*let shang = this.outFilters.length / 4
      const yu = this.outFilters.length % 4
      shang = (yu > 0 || shang < 1) ? shang + 1 : shang
      shang = shang * 50 + 200*/
      return `calc(100vh - 340px)`
    }
  },
  created() {
    this.loadFilters()
  },
  methods: {
    loadFilters() {
      if (!this.excelOut.outId) {
        return
      }
      this.$post('excelFilter/queryPage', {
        page: 1, pageSize: -1,
        filters: [ {field: 'outId', op: '=', value: this.excelOut.outId}],
        sorts: [ { field: 'filterOrder', asc: true }]
      }).then(res => {
        this.outFilters.splice(0, this.outFilters.length)
        if (res.code === 200) {
          res.data.records.forEach(item => {
            if (item.filterType === '选项') {
              item.sources = this.$Util.toArray(item.filterSource)
            }
            this.outFilters.push(item)
          })
          this.clearQuery()
        }
      })
    },
    clearQuery() {
      const { columns, datas } = this.queryData
      if (columns && columns.length > 0) {
        columns.splice(0, columns.length)
      }
      if (datas && datas.length > 0) {
        datas.splice(0, datas.length)
      }
    },
    searchSource(compute) {
      this.loading = true
      this.args.compute = compute
      this.$post('excelTemplate/queryData/' + this.excelOut.outId, this.args)
          .then(res => {
            this.$resultMsg(this, res, '查询失败', true)
            this.pageInfo.page = 1
            this.clearQuery()
            if (res.code === 200) {
              this.$Util.copyAttr(res.data, this.queryData, null, this)
              this.pageSource()
            }
            this.loading = false
          })
    },
    clearArgs() {
      this.$Util.cleanObj(this, this.args)
    },
    exportExcel() {
      this.loading = true
      this.args.compute = true
      this.args.report = true
      this.$post('excelTemplate/exportExcel/' + this.excelOut.outId, this.args)
          .then(res => {
            this.args.compute = false
            this.args.report = false
            this.$resultMsg(this, res)
            this.loading = false
            if (res.code === 200 && res.data) {
              let raw = window.atob(res.data) // 解码base64得到二进制字符串
              let rawLength = raw.length
              let uInt8Array = new Uint8Array(rawLength) // 创建8位无符号整数值的类型化数组
              for (let i = 0; i < rawLength; ++i) {
                uInt8Array[i] = raw.charCodeAt(i) // 数组接收二进制字符串
              }
              // const blob = new Blob([uInt8Array], {type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'})
              const blob = new Blob([uInt8Array], {type: 'application/vnd.ms-excel.sheet.macroEnabled.12'})
              const downloadElement = document.createElement('a')
              let href = blob
              if (typeof blob === 'string') {
                downloadElement.target = '_blank'
              } else {
                href = window.URL.createObjectURL(blob) // 创建下载的链接
              }
              downloadElement.href = href
              downloadElement.download = this.excelOut.outName // 下载后文件名
              document.body.appendChild(downloadElement)
              downloadElement.click() // 触发点击下载
              document.body.removeChild(downloadElement) // 下载完成移除元素
              if (typeof blob !== 'string') {
                window.URL.revokeObjectURL(href) // 释放掉blob对象
              }
            }
          })
    },
    handleCurrentChange(val) {
      this.pageInfo.page = val
      this.pageSource()
    },
    handleSizeChange(val) {
      this.pageInfo.pageSize = val
      this.pageSource()
    },
    pageSource() {
      const { page, pageSize, dataSource } = this.pageInfo
      dataSource.splice(0, dataSource.length)
      const { datas } = this.queryData
      this.pageInfo.total = datas.length
      const start = (page - 1) * pageSize
      const end = page * pageSize
      for (let i = start; i < end; i++) {
        if (i >= this.pageInfo.total) {
          break
        }
        dataSource.push(datas[i])
      }
    }
  }
}
</script>

<style lang="scss">
 .bl-result {
   .el-table .cell {
     padding: 2px 0;
   }
 }
</style>
